import { defineStore } from 'pinia'
import i18n from '@/extensions/i18n'
import { useConfigStore } from '@/stores/config'
import {loadLocaleMessages} from '@/extensions/i18n'
export const useLocalConfigStore = defineStore('localConfig', {
  state: () => {
    let localConfigKey = 'localConfig';
    const defaultData = { 
      theme:'',
      language:''
    };
    let localConfigStr = localStorage.getItem(localConfigKey);
    const localConfig = localConfigStr ? JSON.parse(localConfigStr) : defaultData;
    if(localConfig.theme){
      document.documentElement.setAttribute('data-theme', localConfig.theme);
    }
    return {
      local_data_key:localConfigKey,
      config:localConfig
    }
  },
    actions: {
      changeTheme(theme){
        if(theme){
          document.documentElement.setAttribute('data-theme', theme);
        }else {
          document.documentElement.removeAttribute('data-theme');
        }
        this.config.theme = theme;
        this.save('theme');
      },
      async changeLanguage(language){
        const configStore = useConfigStore()
        const locales = configStore.config.locales || ['en','zh-CN'];
        if(!locales.includes(language)){ //支持的语言
          return;
        }
        if (!i18n.global.availableLocales.includes(language)) { //没有语言包,懒加载语言包
          loadLocaleMessages(language)
        }
        if (i18n.mode === 'legacy') {
          i18n.global.locale = language
        } else {
          i18n.global.locale.value = language
        }
        document.querySelector('html').setAttribute('lang', language)
        if(this.config.language === language){
          return;
        }
        this.config.language = language;
        this.save('language');
      },
      save(key){
        let configStr = localStorage.getItem(this.local_data_key) || '{}';
        let config = JSON.parse(configStr);
        config[key] = this.config[key];
        localStorage.setItem(this.local_data_key,JSON.stringify(config));
      }
    },
     getters: {
       theme: (state) => state.config.theme  || '',
       language: (state) => state.config.language,
    },
})